﻿using System;
using System.Diagnostics;
using System.Windows.Forms;
using StockTrader.Platform.Logging;

namespace StockTrader.UI.Trader
{
    class Program
    {
        public static void Main(string[] args)
        {
            OfflineAnalyzer chart = new OfflineAnalyzer();
            LiveTrader login = new LiveTrader();
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
            int traderCode = 0;
            int numDays = -1;
            bool isAutoStart = false;

            if (args.Length > 0)
            {
                if (int.TryParse(args[0], out traderCode)) ;
                if (args.Length > 1 && int.TryParse(args[1], out numDays))
                    chart.DaysToAnalyze = -numDays;
                if (args.Length > 2 && bool.TryParse(args[2], out isAutoStart))
                    chart.IsAutoStart = isAutoStart;
            }

            if (traderCode == 1)
                Application.Run(chart);
            else
                Application.Run(login);
           
        }

        static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
        {
            var errMsg = "Error:\n" + e.ExceptionObject.ToString() + "\n\nRestarting the process...";
            FileTracing.TraceOut(errMsg);
            MessagingUtils.SendAlertMessage("Unhandled Exception", errMsg, "Unhandled Error, Restarting the process...");
            ProcessStartInfo start = new ProcessStartInfo();
            string exeLocation = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            // Enter the executable to run, including the complete path 
            start.FileName = exeLocation;

            // Do you want to show a console window? 
            start.WindowStyle = ProcessWindowStyle.Normal;// Hidden;
            start.CreateNoWindow = false;// true;

            //using (Process proc = Process.Start(start))
            //{
            //}
            Environment.Exit(1);
        }
    }
}
